package com.feng.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: 丰
 * @date: 2023/1/11 15:57
 */
@Configuration
public class RabbitMqConfig {

    // 定义一个交换机名称
    private final String TOPIC_EXCHANGE = "feng.exchanges.topic";

    @Bean
    RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 确认模式，需要重写确认回调函数
        rabbitTemplate.setConfirmCallback((CorrelationData correlationData, boolean ack, String cause) -> {
            if (!ack){
                System.out.println("消息发送到交换机失败，ack=false" + cause);
                throw new RuntimeException(cause);
            }else {
                System.out.println("消息投递到exchange成功");
            }
        });

        rabbitTemplate.setReturnsCallback((ReturnedMessage returned) -> {
            System.out.println("消息发到队列失败，请检查交换机或路由:" + returned);
            throw new RuntimeException("消息发到队列失败，请检查交换机或路由");
        });
        // 设置消息转换成json格式，这个配置不是必须
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        // 设置应答时长
        rabbitTemplate.setReplyTimeout(6000);
        return rabbitTemplate;
    }

    // 创建交换机
    @Bean
    public TopicExchange topicExchange(){
        // 参数：交换机名称，是否持久化，是否自动删除
        return new TopicExchange(TOPIC_EXCHANGE, true, false);
    }

    // 创建队列
    @Bean
    public Queue studentQueue(){
        return new Queue("feng.send", true);
    }

    // 创建连接（Binding）
    @Bean
    public Binding topicExchangeToStudentQueueBinding(){
        return BindingBuilder
                .bind(studentQueue())
                .to(topicExchange())
                .with("feng.send.*");
    }
}
